package com.chat.chat.socket;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.chat.beans.ChatVo;
import com.chat.chat.beans.kefu;
import com.chat.chat.service.ChatService;
import com.chat.chat.service.KefuService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{id}/{kefuId}")
public class WebSocket {

    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id,@PathParam(value = "kefuId") String kefuId) {
        this.session = session;
        if (sessionPool.containsKey(id)) {
            sessionPool.remove(id);
            sessionPool.put(id, session);
        } else {
            sessionPool.put(id, session);
            webSockets.add(this);
        }
        ChatVo chatVo = new ChatVo();
        chatVo.setId(Integer.parseInt(id)).setTo(22).setType("3").setMsg("用户"+id+"有新消息").setNowTime(new Date());
        String msg = jsonToString(chatVo);
        System.out.println("用户id" + id + "【websocket消息】有新的连接，总数为:" + webSockets.size());
        System.err.println(kefuId);
        if (!kefuId.equals(0)){
            sendOneMessage(kefuId, msg);
        }

    }

    @OnClose
    public void onClose(@PathParam(value = "id") String id) {
//        webSockets.remove(this);
        if (sessionPool.containsKey(id)) {
            sessionPool.remove(id);
            //从set中删除
            webSockets.remove(this);
        }
        System.out.println("用户id" + id + "连接断开，总数为:" + webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            ChatVo person = objectMapper.readValue(message, ChatVo.class);
            person.setNowTime(new Date());
            System.out.println("【websocket消息】收到客户端消息:" + person);
                sendOneMessage(person.getTo().toString(), message);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public void sendOneMessage(String id, String message) {
        System.out.println("【websocket消息】单点消息:" + message);
        Session session = sessionPool.get(id);
        if (session != null) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    public void sendAllMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:" + message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String jsonToString(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(obj);
            return jsonString;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ChatVo toJson(String obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            ChatVo person = objectMapper.readValue(obj, ChatVo.class);
            return person;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


}


